//
//  T3FTNPOIManager.swift
//  t3_map
//
//  Created by Cunhai Li on 2024/12/12.
//

import Foundation
import Flutter
import QMapKit

class T3FTNPOIManager: NSObject {

    private let search = QMSSearcher()
    private var strongSelf: T3FTNPOIManager?
    private var result: FlutterResult?

    func regeo(arguments: Any?, result: @escaping FlutterResult) {

        self.result = result

        /// arguments示例：
        /// ```
        /// {
        ///    "longitude": 11.111
        ///    "latitude": 11.111
        /// }
        /// `
        do {
            let json = try T3FJsonUtil.toJson(arguments)
            if let coordinate = jsonToCoordinate2D(json: json) {

                /// 保持引用
                strongSelf = self
                search.delegate = self

                let option = QMSReverseGeoCodeSearchOption()
                option.setLocationWithCenter(coordinate)
                search.searchWithReverseGeoCodeSearchOption(option)
            }
            else {
                let response = ["error": T3FTNPOIManagerError.dataParseFail.localizedDescription]
                let value = try? T3FJsonUtil.toString(response)
                self.result?(value)
            }
        } catch (let error) {
            let response = ["error": error.localizedDescription]
            let value = try? T3FJsonUtil.toString(response)
            self.result?(value)
        }
    }

    private func jsonToCoordinate2D(json: [String: Any]) -> CLLocationCoordinate2D? {
        guard let longitude = json["longitude"] as? Double,
              let latitude = json["latitude"] as? Double
        else { return nil }

        return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }

    deinit {
        print("deinit poi manager")
    }
}

extension T3FTNPOIManager: QMSSearchDelegate {
    func search(with reverseGeoCodeSearchOption: QMSReverseGeoCodeSearchOption, didReceive reverseGeoCodeSearchResult: QMSReverseGeoCodeSearchResult) {

        defer { strongSelf = nil }

        var json = [String : Any]()
        json["cityCode"] = reverseGeoCodeSearchResult.ad_info.phone_area_code
        json["city"] = reverseGeoCodeSearchResult.ad_info.city
        json["adCode"] = reverseGeoCodeSearchResult.ad_info.adcode
        json["district"] = reverseGeoCodeSearchResult.ad_info.district
        json["address"] = reverseGeoCodeSearchResult.address
        if let shortAddress = reverseGeoCodeSearchResult.formatted_addresses?.recommend {
            json["shortAddress"] = shortAddress
        }
        let value = try? T3FJsonUtil.toString(json)
        self.result?(value)
    }

    func search(with searchOption: QMSSearchOption, didFailWithError error: Error) {
        defer { strongSelf = nil }

        let response = ["error": error.localizedDescription]
        let value = try? T3FJsonUtil.toString(response)
        self.result?(value)
    }
}

private enum T3FTNPOIManagerError: Error {
    case dataParseFail
    case noResult
}

extension T3FTNPOIManagerError: CustomStringConvertible {

    var description: String {
        switch self {
        case .dataParseFail:
            return "数据解析异常"
        case .noResult:
            return "未查询到逆地理信息"
        }
    }
}
